<template>
	<view class="page-container">
		<view class="search-container">
			<view class="search">
				<u-search @click="show = true" :show-action="false" placeholder="搜索" :disabled="true"></u-search>
			</view>
		</view>
		<view>
			<u-popup v-model="show" mode="right" length="90%">
				<view
					style="font-size: 18px;border-bottom: 1px solid #aaa;font-weight: bold;padding: 10px;display: flex;justify-content: space-between;">
					<!-- <u-icon name="/static/image/ss.png" size="65"></u-icon> -->
					<text class=" padding-left-sm" style="color: #3E97B0;">筛选</text>
					<text @click="show=false">关闭</text>
				</view>
				<!-- class="form"  -->
				<u-form class="form" style="padding: 0 10px;" :model="query" ref="uForm" label-position="left">
					<!-- :inputStyle="inputStyle" --><!-- bg-color="#fff" -->
					<!-- <view class="padding-sm flex" >
						
					  <view style="width: 100%"
					      ><u-search
					        placeholder="请扫描存货"
					        v-model="keyword"
					        :show-action="false"
					        :disabled="true"
					        @click="search"
					        searchIconSize="26"
					        :inputStyle="inputStyle"
					      ></u-search
					    ></view>
					    <u-icon
					      name="scan"
					      size="60"
					      class="margin-sm-left flex-sub margin-sm-right"
						  @click="search"
					    ></u-icon>
					  </view> -->
					<u-form-item class="text-bold" label="仓库编码:" prop="whCode" label-width="220">
						<u-input placeholder="请输入" v-model="query.whCode" type="text" maxlength="200"></u-input>
					</u-form-item>
					
					<u-form-item class="text-bold" label="存货名称:" prop="invName" label-width="220">
						<u-input placeholder="请输入" v-model="query.invName" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item class="text-bold" label="存货编码:" prop="invCode" label-width="220">
						<!-- <u-input placeholder="请输入" v-model="query.invCode" type="text" maxlength="200"></u-input> -->
						
						<u-search v-model="query.invCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描" :show-action="false" @search="confirm" bgColor="#fff"></u-search>
						<text class="cuIcon-scan text-xxl margin-right" @click="search" ></text>
					</u-form-item>
					<u-form-item class="text-bold" label="规格:" prop="invStd" label-width="220">
						<u-input placeholder="请输入" v-model="query.invStd" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item class="text-bold" label="批次:" prop="cbatch" label-width="220">
						<u-input placeholder="请输入" v-model="query.cbatch" type="text" maxlength="200"></u-input>
					</u-form-item>
				</u-form>
				<!-- <view class="footer">
				<u-button class="btn" type="primary" @click="submit">查询</u-button>
			</view> -->
				<view class=" flex cu-bar tabbar bg-white foot cu-modal-footer">
					<!-- round -->
					<button class="cu-btn  lines-red lg " @click="reset">重置</button>
					<button class="cu-btn  bg-confirm lg margin-left " @click="submit">查询</button>
				</view>
			</u-popup>
			<!-- <u-calendar v-model="startTime" mode="range" @change="startConfirm" max-date="9999"></u-calendar> -->
			<u-picker mode="time" v-model="startTime" @confirm="startConfirm"></u-picker>
			<u-picker mode="time" v-model="startTime2" @confirm="startConfirm2"></u-picker>
		</view>
		<!-- 表格容器 -->
		<view class="table-container">
			<next-table class="next-table" :show-header="true" :columns="column" :stripe="true" :fit="false" :border="true"
				:data="datalist" :showPaging="true" :pageIndex="query.pageNo" :pageTotal="pageTotal" sum-text="合计" show-summary :summary-method="summaryMethod"
				:pageSize="query.pageSize" :showPageSizeSelector="true" @pageChange="handlePageChange" @pageSizeChange="handlePageSizeChange"></next-table>
		</view>
	</view>
</template>
<script>
	import util from '@/common/fire.js'
	export default {
		options: {
			styleIsolation: 'shared'
		},
		data () {
		        return {
					query: {
						pageNo: 1,
						pageSize: 14,
					},
					focus:false,
					inputStyle:{
					  fontSize:'34rpx',
					  marginRight: '10rpx' ,
					},
					keyword: '',
					show: false,
					startTime: false,
					startTime2: false,
					formDate:'',
					showDate: false,
		            // pageIndex: 1,
		            pageTotal: 0,
					selectList: [],
		            datalist: [],
		            checkNameList: [],
					filters: {},
		            column: [
						{ name: 'xuhao', label: '序号', fixed:true,width:60 ,align:'center',},
						{ name: 'whName', label: '仓库', width:60 , },
		                { name: 'invName', label: '存货名称', width:100,fixed:true,},
		                { name: 'invCode', label: '存货编码', width:90,},
		                { name: 'invStd', label: '规格型号' , width:70,},
						{ name: 'unitName', label: '单位' , width:80,},
						// { name: 'iqty', label: '数量' , width:80,},
						{ name: 'iqty', label: 'U8存量' , width:100,},
						{ name: 'useQty', label: 'WMS占用量' , width:100,},
						{ name: 'syQty', label: '可用量' , width:100,},
						{ name: 'cbatch', label: '批次' , width:120,},
						{ name: 'rgrade', label: '品级', width:70,},	
						// 
		            ]
		        }
		    },
			onReady() {
				
			},
			onLoad(p) {
				if(p.invCode){
					this.query.invCode = p.invCode
					this.query.whCode = p.whCode
				}
				this.getdatalist()
				this.get_rgrade()
				
			},
		    methods: {
				handlePageChange(newPageIndex) {
					this.query.pageNo = newPageIndex;
					this.getdatalist()
				},
				handlePageSizeChange(newPageSize) {
					this.query.pageSize = newPageSize;
					this.getdatalist()
				},

				summaryMethod({columns, data}){
					let sums = [];
					columns.forEach((column, index) => {
					        if (index === 0) {
					            sums[index] = '合计';
					            return;
					        }
					        const values = data.map(item => Number(item[column.name]));
					        const precisions = [];
					        let notNumber = true;
							console.log(values,'values',column.name)
					        values.forEach(value => {
					            if (column.name == 'iqty' || column.name == 'useQty' || column.name == 'syQty') {
					                notNumber = false;
					                let decimal = ('' + value).split('.')[1];
					                precisions.push(decimal ? decimal.length : 0);
					            }
					        });
					        const precision = Math.max.apply(null, precisions);
					        if (!notNumber) {
					            sums[index] = values.reduce((prev, curr) => {
					                const value = Number(curr);
					                if (!isNaN(value)) {
					                    return parseFloat((prev + curr).toFixed(Math.min(precision, 20)));
					                } else {
					                    return prev;
					                }
					            }, 0);
					        } else {
					            sums[index] = '';
					        }
					});
					return sums
				},
				get_rgrade(){
					this.$u.api.dictListData({dictType: 'mf_grade'}).then(res => {
						res.forEach(item =>{
							this.filters[item.dictValue] = item.dictLabel;
						})
						this.filters['-'] = '--';
						// this.column[8]['filters'] = this.filters
						this.column[10]['filters'] = this.filters
					})
				},
				confirm() {
					this.focus = false
					this.commonSearch(this.query.invCode)
				},
				search() {
					var _that = this;
					_that.focus = false
					
					if(this.vuex_config.deviceType === this.vuex_config.deviceTypeAPP){
						const wechat = uni.getSystemInfoSync()?.host?.env
						if (wechat === 'WeChat') {
						    uni.scanCode({
						    	scanType: ["barCode", "qrCode"],
						    	// onlyFromCamera: true,
						    	success: async (res) => {
						    		_that.barCode = res.result;
						    		await _that.commonSearch(res.result)
						    	},
						    });
						} else {
							var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");
							console.log('mpaasScanModule',mpaasScanModule)
							
							mpaasScanModule.mpaasScan({
								// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
								'scanType':  ['qrCode','barCode'],
								// 是否隐藏相册，默认false不隐藏
								'hideAlbum': false,
								//ios需要设置这个参数，只支持中英文 zh-Hans、en，默认中文                       
								'language' : 'en',
								//相册选择照片识别错误提示(ios)
								'failedMsg': '未识别到二维码，请重试',
								//Android支持全屏需要设置此参数
								'screenType': 'full'              
							},
							async (ret) => {
								console.log('ret',ret)
								if(ret.resp_message == 'success'){
									_that.barCode = ret.resp_result;
									await _that.commonSearch(ret.resp_result)
								}
							})
						}
					}else if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
					_that.focus = false
					setTimeout(()=>{
						_that.focus = true
					},500)
				}
					
				},
				makeSound(name){
					console.log("=====testClick=====");
					let src = '/static/'+name+'.mp3';
					//实例化声音  
					const Audio = uni.createInnerAudioContext();
					Audio.autoplay = true;
					Audio.src = src; //音频地址  
					Audio.play(); //执行播放  
					Audio.onError((res) => {
					});
					Audio.onPause(function() {
						console.log('end');
						Audio.destroy();
					});
				},
				async commonSearch(barCode) {
					let that = this
					//扫存货
					if (util.checkBarcode(barCode, this.vuex_config.InventoryPrefix)
					|| util.checkBarcode(barCode, this.vuex_config.cbatchPrefix)) {
						this.$u.api.mf.getBarInfo({
							barCode,
						}).then(res => {
							if(res.result == 'true'){
								if (!res.error) {
									if(res.data.basInv){
										console.log(res,'res')
										this.query.invCode = res.data.basInv.invCode
										this.query.cbatch =  res.data.batchInfo?res.data.batchInfo.u8Batch:''
										this.$forceUpdate()
										setTimeout(()=>{
											that.makeSound("cg");
										},500)
										that.$u.toast('验证成功！');
									}else{
										setTimeout(()=>{
											that.makeSound("sb");
										},500)
										that.$refs.jsError.showError('', '验证失败！', 'error');
									}
									
								} else {
									setTimeout(()=>{
										that.makeSound("sb");
									},500)
									that.$refs.jsError.showError('', res.error, 'error');
								}
							}else{
								setTimeout(()=>{
									that.makeSound("sb");
								},500)
								that.$refs.jsError.showError('', res.message, 'error');
							}
						})
					} else {
						setTimeout(()=>{
							that.makeSound("sb");
						},500)
						this.$refs.jsError.showError('', '请扫描正确的条码！', 'error');
					}
				
					setTimeout(() => {
						this.barCode = '';
					}, 500);
				
				},
				startConfirm(e) {
					this.query.ddate_gte = e.year + "-" + e.month + "-" + e.day;
				},
				startConfirm2(e) {
					this.query.ddate_lte = e.year + "-" + e.month + "-" + e.day;
				},
				getStateValue(item){
				  this.query.ctype = item;
				},
				submit() {
					// this.query.invCode ? this.query.bmustInv = 1 : this.query.bmustInv = ''
					// this.query.whCode ? this.query.bmustWh = 1 : this.query.bmustWh = ''
					setTimeout(() => {
						this.query.pageNo = 1;
						this.loadData();
					}, 100);
				},
				reset() {
					this.query = {
						pageNo: 1,
						pageSize: 14,
					};
					this.loadData();
				},
				dateChange(e) {
					console.log(e);
					this.formDate = e.startDate + ' 至 ' + e.endDate ;
					this.query.ddate_gte = e.startDate
					this.query.ddate_lte  = e.endDate
				},
				loadData(){
					this.show = false;
					this.query.pageNo = 1
					this.getdatalist()
				},
		        getdatalist() {
					this.query.qtyType = 0
					this.$u.api.mf.stockListData(this.query).then((res) => {
						if(!res.list.length){
							this.query.pageNo = 0
						}
						this.datalist = res.list.map((item,index)=>{
							item.xuhao = index+1;
							console.log(item['rgrade'],'rgrade')
							item['rgrade'] ? item['rgrade'] : item['rgrade'] = '-'
							return item
						})
						this.pageTotal = Math.ceil(res.count /this.query.pageSize); 
					});
		        },
		        pageChange(index) {
		            this.query.pageNo = index
		            this.getdatalist()
		        },
		    },
		    created() {
		        // this.getdatalist()
		    }
	}
</script>
<style lang="scss">
	page {
		// background-color: #f8f8f8;
		background-color:#e6e6e6;
		height: 100vh;
		overflow: hidden;
	}

	.page-container {
		display: flex;
		height: 100vh;
		flex-direction: column;
	}

	.search-container {
		background-color: #fff;
		margin-bottom: 10px;
		flex-shrink: 0; /* 防止搜索区域被压缩 */
	}

	.table-container {
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden; /* 防止整个容器溢出 */
		min-height: 0; /* 确保flex子项可以缩小 */
	}
	.cu-bar {
		min-height: 60px;
	}
	
	.cu-btn {
		font-size: 16px;
		height: 40px;
	}
	
	.foot {
		background: #fff;
	}
	.flex-sub{
		margin-left: 10rpx;
	}
	
	.button {
	  font-size: 32rpx;
	  color: #666666;
	  line-height: 40rpx;
	  padding: 12rpx 40rpx;
	  margin-bottom: 20rpx;
	  margin-right: 10rpx;
	  background: #f7f7f7;
	  border-radius: 180rpx;
	}
	.button:hover {
	  background: #3e97b0;
	  color: #ffffff;
	}

	.uni-group {
		display: flex;
		align-items: center;
	}
	.lable-text {
		text-align: justify;
	}
	
	.u-form-item {
		font-size: 28rpx !important;
		padding: 2px !important;
	}
	.footer {
		position: fixed;
		left: 0;
		bottom: 20px;
		width: 100%;
	}
	.cu-modal-footer {
		padding: 32rpx 32rpx;
		width: 100%;
	
		.cu-btn {
			width: 50%;
		}
	}
	.bg-confirm {
		background: #3e97b0;
		color: #ffffff;
	}
	/* 通用表格样式优化 */
	/deep/.next-table {
		height: 100% !important;
		display: flex !important;
		flex-direction: column !important;
		background: #fff;
	}

	/deep/.table-empty {
		height: 100% !important;
		border: none !important;
	}

	/* H5环境样式 */
	/* #ifdef H5 || APP-PLUS */
	/deep/.next-table-content {
		flex: 1 !important;
		display: flex !important;
		flex-direction: column !important;
		overflow: hidden !important;
		min-height: 0 !important;
	}

	/deep/.next-table-scroll {
		flex: 1 !important;
		display: flex !important;
		flex-direction: column !important;
		overflow: hidden !important;
		min-height: 0 !important;
	}

	/* 表头固定 */
	/deep/.next-table-header {
		flex-shrink: 0 !important;
		background: #fafafa !important;
		z-index: 10 !important;
	}

	/* 表体滚动区域 */
	/deep/.next-table-body {
		flex: 1 !important;
		overflow-y: auto !important;
		overflow-x: auto !important;
		min-height: 0 !important;
	}

	/* 合计行固定在底部 */
	/deep/.next-table-footer,
	/deep/.table-h5-footer {
		flex-shrink: 0 !important;
		background: #fafafa !important;
		border-top: 1px solid #e8e8e8 !important;
		z-index: 10 !important;
	}

	/* 分页组件固定在底部 */
	/deep/.table-paging {
		flex-shrink: 0 !important;
		background: #fff !important;
		border-top: 1px solid #e8e8e8 !important;
		z-index: 10 !important;
	}
	/* #endif */

	/* 小程序环境样式优化 */
	/* #ifndef H5 || APP-PLUS */
	/deep/.next-table-applet {
		height: 100% !important;
		display: flex !important;
		flex-direction: column !important;
	}

	/deep/.next-table-content-applet {
		flex: 1 !important;
		display: flex !important;
		flex-direction: column !important;
		overflow: hidden !important;
		min-height: 0 !important;
	}

	/* 小程序表头固定 */
	/deep/.next-table-header {
		flex-shrink: 0 !important;
		background: #fafafa !important;
		z-index: 10 !important;
		position: sticky !important;
		top: 0 !important;
	}

	/* 小程序表体滚动区域 */
	/deep/.next-table-content-applet scroll-view {
		flex: 1 !important;
		min-height: 0 !important;
		max-height: calc(100vh - 200px) !important; /* 为合计行和分页预留空间 */
	}

	/* 小程序表格滚动容器 */
	/deep/.next-table-scroll {
		display: flex !important;
		flex-direction: column !important;
		min-height: 100% !important;
	}

	/* 小程序表体区域 */
	/deep/.next-table-fixed {
		flex: 1 !important;
		min-height: 0 !important;
	}

	/* 小程序合计行 - 在scroll-view内部，可以水平滚动 */
	/deep/.next-table-scroll .table-summary,
	/deep/.next-table-scroll .next-table-footer {
		flex-shrink: 0 !important;
		background: #fafafa !important;
		border-top: 1px solid #e8e8e8 !important;
		z-index: 5 !important;
	}

	/* 小程序表格行样式 */
	/deep/.item-tr {
		display: flex !important;
		min-width: max-content !important;
	}

	/* 小程序表格单元格样式 */
	/deep/.item-td,
	/deep/.item-th {
		flex-shrink: 0 !important;
		white-space: nowrap !important;
	}

	/* 小程序分页组件固定 */
	/deep/.table-paging {
		flex-shrink: 0 !important;
		background: #fff !important;
		border-top: 1px solid #e8e8e8 !important;
		z-index: 10 !important;
		position: sticky !important;
		bottom: 0 !important;
	}
	/* #endif */

	.text-bold {
		font-size: 17px !important;
		padding:10px 0px !important;
	}
	/deep/.u-form-item{
		padding:10px 0px !important;
	}
</style>